# -*- coding: UTF-8 -*-
from urllib import request
from urllib import parse
import json

def fanyi(i):
    # Request URL
    Request_URL = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
    # 创建Form_Data字典，存储得到的Form Data
    Form_Data = {}
    Form_Data['type'] = 'AUTO'
    Form_Data['from'] = 'AUTO'  # 自动检测语言
    Form_Data['to'] = 'AUTO'
    Form_Data['smartresult'] = 'dict'
    Form_Data['doctype'] = 'json'
    Form_Data['version'] = '2.1'
    Form_Data['keyfrom'] = 'fanyi.web'
    Form_Data['action'] = 'FY_BY_REALTIME'
    # 使用urlencode方法转换标准格式
    Form_Data['i'] = i

    data = parse.urlencode(Form_Data).encode('utf-8')
    # 传递Request对象和转换完格式的数据
    response = request.urlopen(Request_URL, data)
    # 读取信息并解码
    html = response.read().decode('utf-8')
    # 使用JSON
    translate_results = json.loads(html)
    # 找到翻译结果
    translate_results = translate_results['translateResult'][0][0]['tgt']
    # 打印翻译信息
    print(translate_results)
if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('string')
    args = parser.parse_args()

    if args.string:
        fanyi(args.string)
